package com.hzit.page.service.impl;

import com.alibaba.fastjson.JSON;
import com.hzit.page.service.IPageService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.system.api.RemoteManagerService;
import com.ruoyi.system.api.domain.Goods;
import com.ruoyi.system.api.domain.GoodsDesc;
import com.ruoyi.system.api.domain.Item;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.context.IContext;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@Service
public class PageServiceImpl implements IPageService {

	@Autowired
	private RemoteManagerService managerService;

	@Autowired
	private TemplateEngine templateEngine;
	//1. 根据商品id生成静态页面
	@Override
	public void createPage(Long goodsId) throws IOException {
		//1.1 定义模板视图
		String templte = "item";
		//1.2 定义上下文对象,用于绑定数据
		Context context = new Context();
		//1.2.1 从远程根据商品id查询出商品对象
		R<Goods> r = managerService.findById(goodsId);
		Goods goods = r.getData();
		//1.2.2 将商品对象放到上下文对象context中
		Map<String, Object> map = new HashMap<>();

		//1.2.3 查询商品描述信息
		R<GoodsDesc> rGoodsDesc = managerService.findGoodsDescById(goodsId);
		GoodsDesc goodsDesc = rGoodsDesc.getData();
		//1.2.4 查询出商品的图片列表
		String itemImagesStr = goodsDesc.getItemImages();
		List<Map> itemImages = JSON.parseArray(itemImagesStr, Map.class);
		//1.2.5 查询自定义扩展属性
		String customAttributeItemsStr = goodsDesc.getCustomAttributeItems();
		List<Map> customAttributeItems = JSON.parseArray(customAttributeItemsStr, Map.class);
		//1.2.6 查询规格及规格选项列表
		String specificationItemsStr = goodsDesc.getSpecificationItems();
		List<Map> specificationItems = JSON.parseArray(specificationItemsStr, Map.class);
		//1.2.7 根据goodsid查询sku商品列表
		R<List<Item>> rSkuList = managerService.findSkuList(goodsId);
		List<Item> items = rSkuList.getData();


		map.put("goods",goods);
		map.put("goodsDesc",goodsDesc);
		map.put("itemImages",itemImages);
		map.put("customAttributeItems",customAttributeItems);
		map.put("specificationItems",specificationItems);
		map.put("items",items);

		context.setVariables(map);

		//1.3 定义输出流,用于将生成的静态页面放在何处保存?
		Writer writer = new FileWriter(new File("D:\\nginx-1.25.1\\html\\item\\" + goodsId + ".html"));

		//1.4 执行模板引擎生成静态页面
		templateEngine.process(templte,context,writer);
	}
}
